<template>
  <h2 align="center" style="width: 100%; justify-content: center; margin-bottom: 32px">创建测评活动</h2>
  <a-space align="center" style="width: 100%; justify-content: center">
    <a-form
      :model="form"
      :style="{ width: '480px' }"
      label-align="left"
      auto-label-width
      @submit="handleSubmit"
    >
      <a-form-item field="appName" label="测评活动名称">
        <a-input v-model="form.appName" placeholder="请输入测评活动名称" />
      </a-form-item>
      <a-form-item field="appDesc" label="测评活动描述">
        <a-input v-model="form.appDesc" placeholder="请输入测评活动描述" />
      </a-form-item>
      <a-form-item field="appIcon" label="测评活动图标">
        <a-space align="start">
          <!-- 文本框，显示最终的 URL -->
          <a-input
            v-model="form.appIcon"
            placeholder="请输入或上传图标链接"
            style="width: 280px"
          />
          <!-- 上传按钮 -->
          <a-upload
            action="http://106.54.212.16:8101/api/file/upload"
            :data="{ biz: 'app_icon' }"
            accept="image/*"
            :with-credentials="true"
            :show-upload-list="false"
            @success="handleIconUploadSuccess"
            @error="handleIconUploadError"
          >
            <a-button type="outline" size="small">上传图标</a-button>
          </a-upload>
        </a-space>
        <!-- 缩略预览 -->
        <div v-if="form.appIcon" style="margin-top: 8px">
          <a-image :src="form.appIcon" width="80" height="80" />
        </div>
      </a-form-item>
      <!--      <a-form-item field="appIcon" label="应用图标">-->
      <!--        <PictureUploader-->
      <!--          :value="form.appIcon"-->
      <!--          :onChange="(value) => (form.appIcon = value)"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <a-form-item field="appType" label="测评活动类型">
        <a-select
          v-model="form.appType"
          :style="{ width: '320px' }"
          placeholder="请选择测评活动类型"
        >
          <a-option
            v-for="(value, key) of APP_TYPE_MAP"
            :value="Number(key)"
            :label="value"
            :key="key"
          />
        </a-select>
      </a-form-item>
      <a-form-item field="scoringStrategy" label="评分策略">
        <a-select
          v-model="form.scoringStrategy"
          :style="{ width: '320px' }"
          placeholder="请选择评分策略"
        >
          <a-option
            v-for="(value, key) of APP_SCORING_STRATEGY_MAP"
            :value="Number(key)"
            :label="value"
            :key="key"
          />
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 120px">
          提交
        </a-button>
      </a-form-item>
    </a-form>
  </a-space>
</template>

<script setup lang="ts">
import { defineProps, ref, watchEffect, withDefaults } from "vue";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import {
  addAppUsingPost,
  editAppUsingPost,
  getAppVoByIdUsingGet,
} from "@/api/appController";
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from "@/constant/app";

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => {
    return "";
  },
});

const router = useRouter();

const form = ref({
  appDesc: "",
  appIcon: "",
  appName: "",
  appType: 0,
  scoringStrategy: 0,
} as API.AppAddRequest);

const oldApp = ref<API.AppVO>();

// 加载旧数据
async function loadData() {
  if (!props.id) return;
  const res = await getAppVoByIdUsingGet({ id: props.id as any });
  if (res.data.code === 0 && res.data.data) {
    oldApp.value = res.data.data;
    form.value = { ...res.data.data };
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
}
watchEffect(loadData);

// 上传成功回调
function handleIconUploadSuccess(file: any) {
  // Arco Upload 把服务器返回挂到 file.response
  const res = file.response as { code: number; data: string; message: string };
  if (res.code === 0) {
    form.value.appIcon = res.data;
    message.success("图标上传成功");
  } else {
    message.error("图标上传失败：" + res.message);
  }
}

// 上传失败回调
function handleIconUploadError(err: Error) {
  message.error("图标上传出错：" + err.message);
}

// 提交表单
async function handleSubmit() {
  let res: any;
  if (props.id) {
    res = await editAppUsingPost({ id: props.id as any, ...form.value });
  } else {
    res = await addAppUsingPost(form.value);
  }
  if (res.data.code === 0) {
    message.success("操作成功，3秒后跳转...");
    setTimeout(() => {
      router.push(`/app/detail/${props.id || res.data.data}`);
    }, 3000);
  } else {
    message.error("操作失败：" + res.data.message);
  }
}

/**
 * 加载数据
 */
// const loadData = async () => {
//   if (!props.id) {
//     return;
//   }
//   const res = await getAppVoByIdUsingGet({
//     id: props.id as any,
//   });
//   if (res.data.code === 0 && res.data.data) {
//     oldApp.value = res.data.data;
//     form.value = res.data.data;
//   } else {
//     message.error("获取数据失败，" + res.data.message);
//   }
// };
//
// // 获取旧数据
// watchEffect(() => {
//   loadData();
// });
//
// /**
//  * 提交
//  */
// const handleSubmit = async () => {
//   let res: any;
//   // 如果是修改
//   if (props.id) {
//     res = await editAppUsingPost({
//       id: props.id as any,
//       ...form.value,
//     });
//   } else {
//     // 创建
//     res = await addAppUsingPost(form.value);
//   }
//   if (res.data.code === 0) {
//     message.success("操作成功，即将跳转到测评活动详情页");
//     setTimeout(() => {
//       router.push(`/app/detail/${props.id || res.data.data}`);
//     }, 3000);
//   } else {
//     message.error("操作失败，" + res.data.message);
//   }
// };
</script>
